package com.zxtech.zzm.core.util

import com.orhanobut.logger.Logger

object CodecUtil {
  fun short2bytes(s: Short): ByteArray {
    var s = s
    val bytes = ByteArray(2)
    for (i in 1 downTo 0) {
      bytes[i] = (s % 256).toByte()
      s = (s.toInt() shr 8).toShort()
    }
    return bytes
  }

  fun bytes2short(bytes: ByteArray): Short {
    var s = (bytes[1].toInt() and 0xFF) as Short
    s = (s.toInt() or (bytes[0].toInt() shl 8 and 0xFF00)).toShort()
    return s
  }

  // long类型转成byte数组
  fun longToByte(number: Long): ByteArray {
    var temp = number
    val b = ByteArray(8)
    for (i in b.indices) {
      b[i] = (temp and 0xff.toByte()
          .toLong()).toByte() // 将最低位保存在最低位
      temp = temp shr 8 // 向右移8位
    }
    //printHexString(b);
    return b
  }

  fun byteToInt2(b: ByteArray): Int {
    val mask = 0xff
    var temp = 0
    var n = 0
    for (i in b.indices) {
      n = n shl 8
      temp = b[i].toInt() and mask
      n = n or temp
    }
    return n
  }

  /**
   * 将指定byte数组以16进制的形式打印到控制台
   *
   * @param hint String
   * @param b byte[]
   * @return void
   */
  fun printHexString(b: ByteArray) {
    Logger.d(formatHexString(b))
  }

  fun formatHexString(b: ByteArray): String {
    var hexstr = ""
    for (i in b.indices) {
      var hex = Integer.toHexString(b[i].toInt() and 0xFF)
      if (hex.length == 1) {
        hex = "0$hex"
      }
      hexstr += hex.toUpperCase() + " "
    }
    return hexstr
  }

  /**
   * 把16进制字符串转换成字节数组
   *
   * @return byte[]
   */
  fun hexStringToByte(hex: String): ByteArray {
    val len = hex.length / 2
    val result = ByteArray(len)
    val achar = hex.toCharArray()
    for (i in 0 until len) {
      val pos = i * 2
      result[i] = (toByte(achar[pos]) shl 4 or toByte(achar[pos + 1])).toByte()
    }
    return result
  }

  private fun toByte(c: Char): Int {
    val b = "0123456789ABCDEF".indexOf(c)
        .toByte()
    return b.toInt()
  }

  /**
   * 将byte转换为一个长度为8的boolean数组（每bit代表一个boolean值）
   *
   * @param b byte
   * @return boolean数组
   */
  fun getBooleanArray(b: Byte): BooleanArray {
    var b = b
    val array = BooleanArray(8)
    for (i in 7 downTo 0) { // 对于byte的每bit进行判定
      array[i] = b.toInt() and 1 == 1 // 判定byte的最后一位是否为1，若为1，则是true；否则是false
      b = (b.toInt() shr 1) as Byte // 将byte右移一位
    }
    return array
  }
}